package com.hectopascal.goalance.service;

import com.hectopascal.goalance.pojo.Department;
import com.hectopascal.goalance.pojo.dto.UserBack;
import com.hectopascal.goalance.repository.DepartmentRepository;
import com.hectopascal.goalance.service.Ipml.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class DepartmentService implements IDepartmentService {
    @Autowired
    DepartmentRepository departmentRepository;

    @Override
    public Map<String, Object> departmentsGet(Integer page, Integer size, String name, Integer status) {
        Integer total = departmentRepository.findAllDepartmentsPage(name, status).get();
        Integer offset = ( page-1 )*size;
        Optional<List<Department>> optionalDepartments = departmentRepository.findAllDepartments(offset, size, name, status);
        List<Department> departments = optionalDepartments.get();
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("departments", departments);
        return result;
    }

    @Override
    public Department departmentAdd(Department department) {
        Optional<Department> department1=departmentRepository.findByName(department.getName());
        if (!department1.isEmpty()) {
            throw new IllegalArgumentException("部门已存在");
        }
        return departmentRepository.save(department);
    }

    @Override
    public int departmentUpdate(Department department){
        Optional<Department> department1=departmentRepository.findByNameAndId(department.getName(),department.getId());
        if (!department1.isEmpty()) {
            throw new IllegalArgumentException("修改失败！部门已存在");
        }
        return departmentRepository.updateDepartment(department.getName(),department.getDescription(),department.getParentId(),department.getStatus(),department.getId());
    }

    @Override
    public int departmentDelete(Integer id) {
        Optional<Department> department=departmentRepository.findById(id);
        System.out.println("1");
        if (department.isEmpty()) {
            throw new IllegalArgumentException("删除失败！部门不存在");
        }
        System.out.println("2");
        Optional<List<Department>> optionalDepartments = departmentRepository.findByParentId(id);
        if (optionalDepartments.isPresent() && !optionalDepartments.get().isEmpty()) {
            throw new IllegalArgumentException("删除失败！该部门有子部门");
        }
        System.out.println("3");
        Optional<List<UserBack> > optionalUsers = departmentRepository.findByDepartmentId(id);
        if (optionalUsers.isPresent() && !optionalUsers.get().isEmpty()) {
            throw new IllegalArgumentException("删除失败！该部门有员工");
        }
        System.out.println("4");
        return departmentRepository.deleteDepartmentById(id);
    }
}
